<template>
  <div>
    <n-space vertical>
      <n-button type="primary" @click="showModal = true">添加文件推送配置</n-button>

      <n-data-table
        :columns="columns"
        :data="filePushList"
        :pagination="pagination"
      />
    </n-space>

    <n-modal v-model:show="showModal" preset="dialog" title="添加文件推送配置">
      <n-form
        :model="formValue"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        label-width="auto"
      >
        <n-form-item label="配置名称" path="name">
          <n-input v-model:value="formValue.Name" placeholder="请输入配置名称" />
        </n-form-item>
        <n-form-item label="存储类型" path="storageType">
          <n-select
            v-model:value="formValue.StorageType"
            :options="storageOptions"
            placeholder="请选择存储类型"
          />
        </n-form-item>
        <n-form-item label="推送地址" path="endpoint">
          <n-input v-model:value="formValue.Endpoint" placeholder="请输入推送地址" />
        </n-form-item>
        <n-form-item label="访问key" path="accessKey">
          <n-input v-model:value="formValue.AccessKey" placeholder="请输入访问密钥" />
        </n-form-item>
        <n-form-item label="访问密钥" path="accessSecret">
          <n-input v-model:value="formValue.AccessSecret" placeholder="请输入访问密钥" />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-switch v-model:value="formValue.Enable" />
        </n-form-item>
        <div style="display: flex; justify-content: flex-end">
          <n-button round type="primary" @click="handleSubmit">提交</n-button>
        </div>
      </n-form>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref,h, reactive,onMounted, } from 'vue'
import { NButton,useMessage ,FormInst,} from 'naive-ui'
import {getFileStorageConfig,addFileStorageConfig, editFileStorageConfig, StorageConfig,} from "@/api/setting/system";

const message = useMessage()
const showModal = ref(false)
const formRef = ref<FormInst | null>(null)
const  loading = ref(false)

const isEditMode = ref(false) // 添加这行定义

const storageOptions = [
  { label: '本地存储', value: 'local' },
  { label: '阿里云OSS', value: 'oss' },
  { label: '腾讯云COS', value: 'cos' },
  { label: '七牛云', value: 'qiniu' }
]

const formValue = reactive({
  ID: null,
  Name: '',
  StorageType: '',
  Endpoint: '',
  Access_key: '',
  Access_secret: '',
  Enable: true,
  Remark: '',
})


const filePushList = ref<StorageConfig[]>([
  {
    id: 1,
    // key: 1,
    Name: '默认本地存储',
    StorageType: 'local',
    Endpoint: '/var/www/uploads',
    AccessKey: '',
    SecretKey: '',
    Enable: true,
    CreatedAt: new Date().toISOString()
  },
  {
    // key: 2,
    id: 2,
    Name: '阿里云OSS存储',
    StorageType: 'oss',
    Endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
    AccessKey: '',
    SecretKey: '',
    BucketName: 'my-bucket',
    Region: 'oss-cn-hangzhou',
    Enable: true,
    CreatedAt: new Date().toISOString()
  }
])
// 加载存储配置
const loadStorageConfigs = async () => {
  loading.value = true
  try {
    filePushList.value = getFileStorageConfig()
  } catch (error) {
    message.error('加载存储配置失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadStorageConfigs()
})

const rules = {
  name: {
    required: true,
    message: '请输入配置名称',
    trigger: 'blur'
  },
  storageType: {
    required: true,
    message: '请选择存储类型',
    trigger: 'blur'
  },
  pushUrl: {
    required: true,
    message: '请输入推送地址',
    trigger: 'blur'
  }
}

const columns = [
  {
    title: 'ID',
    key: 'ID'
  },
  {
    title: '配置名称',
    key: 'Name'
  },
  {
    title: '存储类型',
    key: 'StorageType',
    render(row) {
      return storageOptions.find(opt => opt.value === row.StorageType)?.label || row.StorageType
    }
  },
  {
    title: '推送地址',
    key: 'Endpoint'
  },
  {
    title: '描述信息',
    key: 'Remark'
  },
  {
    title: '状态',
    key: 'Enable',
    render(row) {
      return row.status ? '启用' : '禁用'
    }
  },
  {
    title: '操作',
    key: 'actions',
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            onClick: () => handleEdit(row)
          },
          { default: () => '编辑' }
        ),
        h(
          NButton,
          {
            size: 'small',
            style: 'margin-left: 5px',
            onClick: () => handleDelete(row.key)
          },
          { default: () => '删除' }
        )
      ]
    }
  }
]

const pagination = reactive({
  pageSize: 10
})

const handleEdit = (row) => {
  Object.assign(formValue, row)
  showModal.value = true
}

const handleDelete = (key) => {
  filePushList.value = filePushList.value.filter(item => item.id !== key)
  message.success('删除成功')
}

// 添加 resetForm 方法
const resetForm = () => {
  Object.assign(formValue, {
    key: null,
    name: '',
    endpoint: '',
    accessKey: '',
    accessSecret: '',
    enable: true,
    remark: '',
  })
  isEditMode.value = false
}

const handleSubmit = async (e) => {
  e.preventDefault()
  try {
    // 验证表单
    await formRef.value?.validate()

    // 区分编辑和新增模式
    if (isEditMode.value) {
      editFileStorageConfig(id,formValue)
      message.success('配置更新成功')
    } else {

      addFileStorageConfig(formValue)
      message.success('配置添加成功')
    }

    // 重置表单和关闭弹窗
    showModal.value = false
    resetForm()

  } catch (errors) {
    console.error('表单验证失败:', errors)
    if (errors) {
      message.error('请检查表单填写是否正确')
    }
  }
}

</script>

<style scoped>
.n-button {
  margin-bottom: 20px;
}
</style>
